//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;

namespace CommunityServer.Components
{
	/// <summary>
	/// Summary description for SearchRssHandler.
	/// </summary>
	public class SearchRssHandler : BaseSyndicationHandler
	{
        private CSContext csContext = CSContext.Current;
		private SearchQuery query = null;

		public SearchRssHandler()
		{
			query = SearchProvider.Instance().GetSearchQueryFromQueryString(csContext.QueryString);
			query.PageIndex = 0;
			query.PageSize = 10;
			query.SortBy = SearchSort.DateDescending;
		}

	    /// <summary>
	    /// The key used to lookup the feed uniquely in the cache.
	    /// </summary>
	    /// <returns></returns>
	    protected override string CacheKey
	    {
	        get { return string.Format("U:{1}-Q:{0}", SearchProvider.Instance().SearchQueryString(query), csContext.RolesCacheKey); }
	    }

	    /// <summary>
	    /// The Fully Qualifed part of the Url for the current request
	    /// </summary>
	    protected override string BaseUrl
	    {
	        get { return Globals.HostPath(Context.Request.Url); }
	    }

	    /// <summary>
	    /// Builds the actual feed.
	    /// </summary>
	    /// <returns>The cached feed.</returns>
	    protected override CachedFeed BuildFeed()
	    {
	        if(Globals.IsNullorEmpty(query.QueryText) 
				&& !query.HasTags 
				&& (query.UserNamesToSearch == null || query.UserNamesToSearch.Length == 0)
				&& (query.UsersToSearch == null || query.UsersToSearch.Length == 0))
            {
                throw new CSException(CSExceptionType.SearchUnknownError,"No Query Terms");
            }

            SearchResultSet searchResult = CSSearch.Search(query);
            SearchRssWriter writer = new SearchRssWriter(searchResult.Posts,null,this.BaseUrl,GetSearchDescription());

            int lastPostID = searchResult.Posts.Count > 0 ? ((IndexPost)searchResult.Posts[0]).PostID : 0;
            DateTime dt =  searchResult.Posts.Count > 0 ? ((IndexPost)searchResult.Posts[0]).PostDate : DateTime.Now;

            return new CachedFeed(dt,lastPostID.ToString(),writer.GetXml());

	    }


		protected virtual string GetSearchDescription()
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			sb.Append("Search results");
			
			if (!Globals.IsNullorEmpty(query.QueryText))
			{
				sb.Append(" for '");
				sb.Append(query.QueryText);
				sb.Append("'");
			}

			if (query.HasTags)
			{
				if (query.Tags.Length > 1)
					sb.Append(" matching tags ");
				else
					sb.Append(" matching tag ");

				for (int i = 0; i < query.Tags.Length; i++)
				{
					if (i > 0)
					{
						if (query.Tags.Length > 2)
							sb.Append(", ");
						else
							sb.Append(" ");

						if (i == query.Tags.Length - 1)
							sb.Append((query.LogicallyOrTags ? "or " : "and "));
					}

					sb.Append("'");
					sb.Append(query.Tags[i]);
					sb.Append("'");
				}
			}

			if (query.UserNamesToSearch != null && query.UserNamesToSearch.Length > 0)
			{
				if (query.UserNamesToSearch.Length > 1)
					sb.Append(" by users ");
				else
					sb.Append(" by user ");

				for (int i = 0; i < query.UserNamesToSearch.Length; i++)
				{
					if (i > 0)
					{
						if (query.UserNamesToSearch.Length > 2)
							sb.Append(", ");
						else
							sb.Append(" ");

						if (i == query.UserNamesToSearch.Length - 1)
							sb.Append("or ");
					}

					sb.Append("'");
					sb.Append(query.UserNamesToSearch[i]);
					sb.Append("'");
				}
			}

			if (query.UsersToSearch != null && query.UsersToSearch.Length > 0)
			{
				if (query.UsersToSearch.Length > 1)
                    sb.Append(" by user IDs ");
				else
					sb.Append(" by user ID ");

				for (int i = 0; i < query.UsersToSearch.Length; i++)
				{
					if (i > 0)
					{
						if (query.UsersToSearch.Length > 2)
							sb.Append(", ");
						else
							sb.Append(" ");

						if (i == query.UsersToSearch.Length - 1)
							sb.Append("or ");
					}

					sb.Append(query.UsersToSearch[i]);
				}
			}
			
			return sb.ToString();
		}

        protected override void ProcessFeed()
        {
            if(!csContext.SiteSettings.EnableRssSearch)
            {
                Globals.Return404(this.Context);   
            }
            else
            {
                base.ProcessFeed ();
            }
        }


	    protected override Section GetCurrentSection
	    {
	        get { return null; }
	    }
	}
}
